/*
 * Copyright (c) 2006-2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author        Notes
 * 2021-10-10     Sherman       first version
 */

#include <rtthread.h>
#include "hal_data.h"
#include <rtdevice.h>

#define LED_PIN    BSP_IO_PORT_02_PIN_09 /* Onboard LED pins */

static rt_device_t uart4;
extern char buffer[50];
extern int32_t value22;
extern switch1;

//线程准备
static rt_thread_t thread1=RT_NULL;
#define thread_stack 512
#define thread_priority 19
#define thread_timeslice 10
static void thread1_entry(void *para);

rt_align(RT_ALIGN_SIZE)
static rt_thread_t thread2=RT_NULL;
#define thread2_stack 512
#define thread2_priority 17
#define thread2_timeslice 10
static void thread2_entry(void *para);
rt_align(RT_ALIGN_SIZE)
static rt_thread_t thread3=RT_NULL;
#define thread3_stack 512
#define thread3_priority 16
#define thread3_timeslice 12
static void thread3_entry(void *para);

//消息队列准备
static  rt_mq_t mq=RT_NULL;
struct msg{
    rt_uint8_t *data_ptr; //指针存放数据
    rt_uint32_t data_size; // 数据长度
};

//互斥量
static rt_mutex_t thread_mutex=RT_NULL;

void hal_entry(void)
{
    rt_kprintf("\n欢迎使用充电桩进行充电，充电前请拔充电枪\n");
    uart4 = rt_device_find(SAMPLE_UART4_NAME);
    rt_device_open(uart4, RT_DEVICE_FLAG_RX_NON_BLOCKING|RT_DEVICE_FLAG_TX_BLOCKING);
    //点击启动充电，同时监听mq是否有充电停止信号

    //绝缘检测 

    //停止充电，同时发送停止充电mq信息

    while (1)
    {
        rt_pin_write(LED_PIN, PIN_HIGH);
        rt_thread_mdelay(500);
        rt_pin_write(LED_PIN, PIN_LOW);
        //rt_thread_mdelay(500);
        rt_device_write(serial, 0, str, (sizeof(str)-1));
    }
}

static void thread1_entry(void *para){
    rt_kprintf("current thread1 \n");
    rt_err_t uwret=RT_EOK;
    char *r_recv;
    int *r_recv2;

    while(1){
        rt_mutex_take(thread_mutex, RT_WAITING_FOREVER);
        uwret = rt_mq_recv(mq, &r_recv2, sizeof(r_recv2), RT_WAITING_FOREVER);
        if(uwret==RT_EOK){
            rt_kprintf("接收停止充电信息 %d \n",r_recv2);
        }else {
            rt_kprintf("no receive \n");
        }
        rt_mutex_release(thread_mutex);
        rt_thread_mdelay(300);
    }
}

static void thread2_entry(void *para){
    rt_kprintf("current thread2 \n");
    rt_err_t uwret;
    uint8_t *i=0;
    while(1){
    rt_mutex_take(thread_mutex, RT_WAITING_FOREVER);
    uwret=rt_mq_send(mq, &i, sizeof(i));
    if(uwret==RT_EOK){
           rt_kprintf("发送停止充电信息 %d \n",i);
        }
    i++;
    rt_mutex_release(thread_mutex);
    rt_thread_mdelay(300);
    }
}







